var app = getApp(),
  fn = app.fn;
var QQMapWX = require("../../utils/qqmap-wx-jssdk.js");
var qqmapsdk;
Page({
  data: { 
    isLoadEnd : true,
    filterData: [
      {
        "type": 'take_off',
        "text": '起送费(单选)',
        "content": [{
          'name': '全部',
          'value': '-1',
          'selected': false
        },
        {
          'name': '0起送费',
          'value': '0',
          'selected': false

        },
        {
          'name': '非0起送费',
          'value': '1',
          'selected': false

        }
        ]
      },
      {
        "type": 'is_guanzhu',
        "text": '关注(单选)',
        "content": [{
          'name': '全部',
          'value': '-1',
          'selected': false

        },
        {
          'name': '不关注',
          'value': '0',
          'selected': false

        },
        {
          'name': '关注',
          'value': '1',
          'selected': false

        }
        ]
      },
      {
        "type": 'favourable',
        "text": '优惠活动(单选)',
        "content": [{
          'name': '全部',
          'value': '-1',
          'selected': false

        },
        {
          'name': '没有优惠活动',
          'value': '0',
          'selected': false

        },
        {
          'name': '有优惠活动',
          'value': '1',
          'selected': false

        }
        ]
      },
      {
        "type": 'tags',
        "text": '店铺标签(单选)',
        "content": [{
          'name': '全部',
          'value': '-1',
          'selected': false

        },
        {
          'name': '没有标签',
          'value': '0',
          'selected': false

        },
        {
          'name': '有标签',
          'value': '1',
          'selected': false

        }
        ]
      },
      {
        "type": 'rank_level',
        "text": '店铺级别(可多选)',
        "more": true,
        "content": [{
          'name': '初级',
          'value': '0',
          'selected': false
        },
        {
          'name': '中级',
          'value': '1',
          'selected': false
        },
        {
          'name': '高级',
          'value': '2',
          'selected': false
        }
        ]
      },
      {
        "type": 'shipping',
        "text": '配送方式(单选)',
        "content": [{
          'name': '全部',
          'value': '-1'
        },
        {
          'name': '平台配送',
          'value': 'tc_express'
        },
        {
          'name': '商家配送',
          'value': 'sj_express'
        }
        ]
      },
    ],
    sortStatus: false,
    filterStatus: false,
    modalStatus: false,
    sortIndex: 0,
    sortType: '',
    wd: '',
    jd: '',
    tc_id: '',
    address: '',
    banner: {
      data: [],
      reqData: {
        type: 3
      }
    },
    agePro: [],
    hotPro: {
      data: [],
      loading: false,
      loadend: false,
      reqData: {

      }
    }

  },
  //遮罩显示
  showModal : function(){
    this.setData({
      modalStatus: true
    })
  },
  //遮罩隐藏
  hideModal : function(){
    this.setData({
      modalStatus: false,
      filterStatus :false,
      sortStatus : false
    })
  },
  showSortClose: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.id;
  
    this.setData({
      sortStatus: (!that.data.sortStatus),
      filterStatus: false,
      sortIndex: index
    });
    if (this.data.sortStatus) {
      this.scrollToTab();
      this.showModal();
    } else {
       this.hideModal();
    }
  },
  //滚动到tab 位置
  scrollToTab : function(){
    let that = this;
    let query = wx.createSelectorQuery();
    query.select("#sort").boundingClientRect();
    query.select(".header").boundingClientRect();
    query.selectViewport().scrollOffset();//这段代码的意思是获取页面滑动位置的查询请求
    query.exec(function (res) {  
      var height = res[0].top - res[1].height - 5;
      if(res[2].scrollTop > 0){
        height = res[0].top - res[1].height - 5 + res[2].scrollTop;
      }
      wx.pageScrollTo({
          scrollTop: height
      })
    });
  },
  onShareAppMessage: function (res) {
    var that = this;
    if (res.from === 'button') {

    }
    return {
      title: '同城e优购',
      path: '方便同城用户生活住行',
    }
  },

  showFilterClose: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.id;
    this.setData({
      filterStatus: (!that.data.filterStatus),
      sortStatus: false,
      sortIndex: index
    });
    if (this.data.filterStatus) { 
      this.scrollToTab();

       this.showModal();
    } else {
      this.hideModal();
    }
  }, 
  showFilterClose2: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.id;
    this.setData({
      filterStatus: (!that.data.filterStatus),
      sortStatus: false,
      sortIndex: index
    });
    that.getInitData();
    if (this.data.filterStatus) {
      //this.showModal();
    } else {
      // this.hideModal();
    }
  },
  sortType: function (e) {

    let sortType = e.currentTarget.dataset.type;
    let filterIndex = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    let selectIndex = e.currentTarget.dataset.selectindex;



    let filterData = 'filterData[' + index + '].selected';
    let filter_content = 'filterData[' + index + '].content[' + selectIndex + '].selected';

    let moreFilterData = 'filterData[' + index + '].content[' + selectIndex + '].selected';
    let that = this;

    this.setData({
      "hotPro.loadend": false,
    });
    
    if (this.data.sortStatus) {
      this.setData({
        sortStatus: (!that.data.sortStatus),
        filterStatus: false,
        sortType: sortType,
      });

      that.setData({
        "hotPro.reqData.type": sortType,
        "tc_id": '',
      });

      this.setData({
        sortIndex: index
      });
      that.getInitData();

    }
    that.setData({
      "hotPro.reqData.page": 1,
    });
    switch (sortType) {
      case 'take_off':
        that.setData({
          "hotPro.reqData.take_off": filterIndex,
        });
        break;
      case 'is_guanzhu':
        that.setData({

          "hotPro.reqData.is_guanzhu": filterIndex,
        });
        break;
      case 'favourable':  //待发货

        that.setData({

          "hotPro.reqData.favourable": filterIndex,
        });
        break;
      case 'tags':  //待收货
        that.setData({

          "hotPro.reqData.tags": filterIndex,
        });
        break;
      case 'rank_level':  //已完成
        that.setData({

          "hotPro.reqData.rank_level": filterIndex,
        });


        break;
      case 'shipping':  //已完成
        that.setData({

          "hotPro.reqData.shipping": filterIndex,
        });


        break;
    }


    if (this.data.filterStatus) {

      let attmoreFlag = this.data.filterData[index].content[selectIndex].selected;
      if (sortType == 'rank_level') {
        this.setData({
          sortType: sortType,
          [moreFilterData]: !attmoreFlag
        });

        return;
      }

      let attFlag = this.data.filterData[index].content[selectIndex].selected;
      for (var i = 0; i < this.data.filterData[index].content.length; i++) {
        this.data.filterData[index].content[i].selected = false;
      }
      if (attFlag) {


        switch (sortType) {
          case 'take_off':  //全部订单
            that.setData({
              "hotPro.reqData.take_off": '',
            });
            break;
          case 'is_guanzhu':  //待付款
            that.setData({

              "hotPro.reqData.is_guanzhu": '',
            });
            break;
          case 'favourable':  //待发货

            that.setData({

              "hotPro.reqData.favourable": '',
            });
            break;
          case 'tags':  //待收货
            that.setData({

              "hotPro.reqData.tags": '',
            });
            break;
          case 'rank_level':  //已完成
            that.setData({

              "hotPro.reqData.rank_level": '',
            });


            break;
          case 'shipping':  //已完成
            that.setData({

              "hotPro.reqData.shipping": '',
            });


            break;
        }

      }
      this.setData({
        sortType: sortType,
        [filterData]: filterIndex,
        [filter_content]: !attFlag
      });
    }
  },

  distanceMark: function (e) {

    this.setData({
      "hotPro.loadend": false,
      "tc_id": '',
    });
    this.scrollToTab();
    var that = this;
    that.setData({

      "hotPro.reqData": "",
    });
    let index = e.currentTarget.dataset.id;

    var id = e.currentTarget.dataset.id,
      url;
    switch (id) {
      case '0':  //全部订单
        url = '../orderList/orderList?orderStatus=0';
        break;
      case '1':  //待付款
        url = '../orderList/orderList?orderStatus=1';
        break;
      case '2':  //待发货

        that.setData({

          "hotPro.reqData.type": 'distance1',
        });
        break;
      case '3':  //待收货
        that.setData({

          "hotPro.reqData.type": 'pingfen',
        });
        break;
      case '4':  //已完成
        that.setData({

          "hotPro.reqData.type": 'order_num',
        });


        break;
    }
    this.setData({
      sortIndex: index
    });

    that.getInitData();
  },

  dwreLoad: function () {
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {

        var latitude = res.latitude;
        var longitude = res.longitude;
        var speed = res.speed;
        var accuracy = res.accuracy;

        qqmapsdk = new QQMapWX({
          key: 'XVZBZ-N4DK3-66C3A-3RJ2N-MH6JT-BUBGH'
        });

      }
    });

  },


  onPullDownRefresh: function () {

    this.getInitData(function () {
      wx.stopPullDownRefresh();
    });
  },

  onReachBottom: function () {
    this.getMore();
  },

  checkSetting: function () {
    var that = this;

    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          app.checkSession()
        } else {
          wx.navigateTo({
            url: '../userInfoLogin/index',
          })
        }
      }
    })
  },

  getInitData: function (callBack) {
    var that = this,
      flag = 0;
    this.hideModal();

    fn.apiData({
      url: 'take_out.php',
      data: {
        act: 'banner'
      },

      success: function (res) {
        if (res.data) {

          apiFinish();

          that.setData({ 'banner.data': res.data.data });
        }
      }
    });


    fn.apiData({
      url: 'take_out.php',
      data: {
        act: 'menu'
      },
      success: function (res) {
        if (res.data.code == 0) {
          apiFinish();

          that.setData({ 'agePro': res.data.data });

        }
      }
    });


    that.setData({
      "hotPro.reqData.act": 'takeout_list',
      "hotPro.reqData.page": 1,
      "hotPro.reqData.lng": app.globalData.lng,
      "hotPro.reqData.tc_id": that.data.tc_id,
      "hotPro.reqData.location_status": '2',
      "hotPro.reqData.lat": app.globalData.lat,
    });
    fn.apiData({
      url: 'stores.php',

      data: that.data.hotPro.reqData,
      success: function (res) {
        if (res.data.code == 0) {


          var newData = res.data.data;
          if (newData == null || !newData) {

            that.setData({
              'hotPro.data': newData,
              'hotPro.loadend': true
            });
            apiFinish();
          } else {

            apiFinish();

            //   that.setData({ 'hotPro.data': res.data.data });

            // newData = that.data.hotPro.data.concat(newData);
            that.setData({
              'hotPro.data': newData,
              'hotPro.loading': false,
              isLoadEnd : false
            });
          }
        }
      }
    });

    
    function apiFinish() {
      ++flag;
      if (flag >= 3) {
        wx.hideToast();
        if (!!callBack) callBack();
      }
    }
  },

  menuClick: function (e) {
    var that = this;

    this.scrollToTab();
    var id = e.currentTarget.dataset.id;
    that.setData({
      tc_id: id,
      "hotPro.reqData.page": 1,
      "hotPro.loadend": false,

    });

    that.getInitData();
  },

  bannerClick: function (e) {
    var type = e.currentTarget.dataset.type;
    var id = e.currentTarget.dataset.id;
    var url = '../';

    switch (type) {
      case 1:

        url += 'buyCart/buyCart';
        break;
    }

    url += '?id=' + id;
    wx.navigateTo({ url: url })
  },

  getMore: function () {
    var that = this,
      page = ++that.data.hotPro.reqData.page;

    if (that.data.hotPro.loadend || that.data.hotPro.loading) return false;

    that.setData({
      "hotPro.loadend": false,
      "hotPro.reqData.page": page
    });

    fn.apiData({
      url: 'stores.php',
      lng: that.data.jd,
      location_status: '2',
      lat: that.data.wd,
      page: page,
      data: that.data.hotPro.reqData,
      success: function (res) {
        if (res.data.code == 0) {
          var newData = res.data.data;
          if (newData == null || !newData) {

            that.setData({
              'hotPro.loadend': true
            });
          } else {

            if (that.data.hotPro.data != null) {
              newData = that.data.hotPro.data.concat(newData);

            }
            that.setData({
              'hotPro.data': newData,
              'hotPro.loading': false
            });
          }


          wx.hideToast();
        }
      }
    });
  },

  onLoad: function () {
    //  app.checkSession();
    var self = this;
     
      if (app.globalData.uid != null) { 
          self.checkSetting();

      } else {
        this.checkSetting();
      }

  },

  onReady: function () {
    var that = this
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.getLocation({
      type: 'wgs84',
      success: function (t) {
        var e = t.latitude, s = t.longitude, n = e + "," + s;
        qqmapsdk = new QQMapWX({
          key: 'XVZBZ-N4DK3-66C3A-3RJ2N-MH6JT-BUBGH'
        });
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: e,
            longitude: s
          },
          coord_type: 1,
          success: function (t) {
            var e = t.result.ad_info.location;
            var ddsd = t.result.address_reference.landmark_l2.title;  //建筑 名字
            that.setData({
              wd: e.lat,
              jd: e.lng,
              address: ddsd
            })
            app.globalData.lat = e.lat;
            app.globalData.lng = e.lng;

            setTimeout(function(){
              var user_id = wx.getStorageSync("user_id");

                  that.setData({
                    "hotPro.reqData.user_id": user_id
                  });
              that.getInitData();
            },1000);
          }
        });
      }
    })
    wx.hideLoading();
  },

})
